package com.nolon.flange.fragment

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.preference.PreferenceManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.nolon.flange.R
import com.nolon.flange.adapter.OrderAdapter
import com.nolon.flange.adapter.PieceAdapter
import com.nolon.flange.databinding.DialogDeleteModifyBinding
import com.nolon.flange.databinding.FragmentFlangeOrderBinding
import com.nolon.flange.extensions.toast
import com.nolon.flange.model.Order
import com.nolon.flange.viewmodel.FlangeViewModel
import com.nolon.flange.viewmodel.OrderViewModel
import com.google.android.material.bottomsheet.BottomSheetBehavior


class FlangeOrderFragment(private val parent: AppCompatActivity) : Fragment() {
    private var _binding: FragmentFlangeOrderBinding? = null
    private val bd get() = _binding!!

    private val flangeViewModel by lazy { ViewModelProvider(parent).get(FlangeViewModel::class.java) }
    private lateinit var sheetBehavior: BottomSheetBehavior<View>

    // adapter
    private val orderAdapter by lazy { OrderAdapter(parent, onOrderItemClick) }
    private val pieceAdapter by lazy { PieceAdapter(parent) }
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentFlangeOrderBinding.inflate(inflater, container, false)
        return bd.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        initView()

        initData()
    }

    private fun initData() {
        val orderVM = OrderViewModel()
        bd.order = orderVM
        with(PreferenceManager.getDefaultSharedPreferences(requireContext())) {
            orderVM.isClearAfterSave.set(
                getBoolean(
                    getString(R.string.pref_clear_after_add),
                    true
                )
            )
            orderVM.holeParamVisibility.set(
                if (getBoolean(getString(R.string.pref_hole_plan), false)) VISIBLE else GONE
            )
            orderVM.isHoleParamOpen.set(
                getBoolean(
                    getString(R.string.pref_hole_plan),
                    false
                )
            )
            orderVM.hasRounding.set(
                getBoolean(getString(R.string.pref_length_rounding), false)
            )
            orderVM.extraVisibility.set(
                if (getBoolean(getString(R.string.pref_enable_extra), false)) VISIBLE else GONE
            )
        }

        with(flangeViewModel) {
            this.orderViewModel = orderVM
            orderVM.addOnChangeCallback()
            orderList.observe(viewLifecycleOwner) {
                orderAdapter.swapData(it)
                pieceAdapter.swapData(flangeViewModel.getGroupParts(it))
                updateProject(orders = it)
            }
        }
    }

    private fun initView() {

        bd.textInstruction.setOnClickListener { showInstruction() }


        bd.recyclerAngleIron.apply {
            adapter = pieceAdapter
            layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
        }


        bd.recyclerOrder.apply {
            adapter = orderAdapter
            layoutManager =
                LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
        }


        sheetBehavior = BottomSheetBehavior.from(bd.cardBottom)

        sheetBehavior.addBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() {
            override fun onStateChanged(bottomSheet: View, newState: Int) {
                when (newState) {
                    BottomSheetBehavior.STATE_HIDDEN -> Unit
                    BottomSheetBehavior.STATE_COLLAPSED -> {
                        bd.imgUpDown.setImageResource(R.drawable.ic_baseline_keyboard_arrow_up_36)
                    }
                    BottomSheetBehavior.STATE_EXPANDED -> {
                        bd.imgUpDown.setImageResource(R.drawable.ic_baseline_keyboard_arrow_down_36)
                    }
                    BottomSheetBehavior.STATE_DRAGGING -> Unit
                    BottomSheetBehavior.STATE_HALF_EXPANDED -> Unit
                    BottomSheetBehavior.STATE_SETTLING -> Unit
                }
            }

            override fun onSlide(bottomSheet: View, slideOffset: Float) = Unit
        })

        // Sheet
        bd.cardTitle.setOnClickListener {
            if (sheetBehavior.state == BottomSheetBehavior.STATE_EXPANDED) {
                sheetBehavior.state = BottomSheetBehavior.STATE_COLLAPSED
                bd.imgUpDown.setImageResource(R.drawable.ic_baseline_keyboard_arrow_up_36)
            }
            if (sheetBehavior.state == BottomSheetBehavior.STATE_COLLAPSED) {
                sheetBehavior.state = BottomSheetBehavior.STATE_EXPANDED
                bd.imgUpDown.setImageResource(R.drawable.ic_baseline_keyboard_arrow_down_36)
            }
        }

        bd.btnAddToOrder.setOnClickListener {
            flangeViewModel.addOrUpdateOrder(it)
        }

    }


    private val onOrderItemClick = { order: Order ->
        val diaView = DialogDeleteModifyBinding.inflate(LayoutInflater.from(context), null, false)
        val dialog = AlertDialog.Builder(requireContext())
        dialog.setView(diaView.root)
        val customDialog = dialog.create()
        diaView.textDelete.setOnClickListener {
            customDialog.cancel()
            flangeViewModel.removeOrder(order)
            toast(context, getString(R.string.delete_success))
        }
        diaView.textModify.setOnClickListener {
            customDialog.cancel()
            sheetBehavior.state = BottomSheetBehavior.STATE_EXPANDED
            flangeViewModel.editOrder(order)
            toast(context, getString(R.string.please_modify))
        }
        customDialog.show()
        closeKeyboard()
    }

    private fun closeKeyboard() {
        val view: View? = activity?.currentFocus
        if (view != null) {
            val imm: InputMethodManager =
                activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(view.windowToken, 0)
        }
    }

    private fun showInstruction() {
        val alertDialog = AlertDialog.Builder(requireContext())
        val instructionPage =
            LayoutInflater.from(requireContext()).inflate(R.layout.dialog_instruction, null)
        alertDialog.setView(instructionPage)
        val instructionDialog = alertDialog.create()
        instructionDialog.show()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        //注意：Fragment 的存在时间比其视图长。请务必在 Fragment 的 onDestroyView() 方法中清除对绑定类实例的所有引用。
        _binding = null
    }

    fun openSheet() {
        when (sheetBehavior.state) {
            BottomSheetBehavior.STATE_HIDDEN, BottomSheetBehavior.STATE_COLLAPSED -> {
                sheetBehavior.state = BottomSheetBehavior.STATE_EXPANDED
                bd.imgUpDown.setImageResource(R.drawable.ic_baseline_keyboard_arrow_down_36)
            }
            else -> Unit
        }
    }

}